<?php
namespace app\frontend\forms;

use Phalcon\Forms\Form;
use app\models\BaseInsName;
use app\frontend\forms\elements\JeDateElement;
use app\frontend\forms\elements\SelectUlElement;
use app\models\Old;
use Phalcon\Db\Column;

class OldSearchForm extends Form
{
    public $search_ins_name;

    public $buy_at_from;

    public $buy_at_to;

    /**
     * @param \Phalcon\Mvc\Model\Criteria|null $query
     * @return \Phalcon\Mvc\Model\Criteria
     */
    public function getQuery(\Phalcon\Mvc\Model\Criteria $query = null)
    {
        $query = $query?$query:Old::query();
        if($this->search_ins_name)
            $query->andwhere("ins_name like :search_ins_name:",['search_ins_name'=>'%'.$this->search_ins_name.'%'],['search_ins_name'=>Column::BIND_PARAM_STR]);
        if($this->buy_at_from)
            $query->andWhere("buy_at > :buy_at_from:",['buy_at_from'=>strtotime($this->buy_at_from)],['buy_at_from'=>Column::BIND_PARAM_INT]);
        if($this->buy_at_to)
            $query->andWhere("buy_at <:buy_at_to:",['buy_at_to'=>strtotime($this->buy_at_to)],['buy_at_to'=>Column::BIND_PARAM_INT]);

        return $query;
    }

    public function initialize()
    {
        $this->setEntity($this);

        $search_ins_name = new SelectUlElement('search_ins_name');

        $search_ins_name->setUserOptions([
            'models'=>BaseInsName::find(),
        ]);

        $this->add($search_ins_name);

        $this->add(
            new JeDateElement(
                "buy_at_from"
            )
        );

        $this->add(
            new JeDateElement(
                "buy_at_to"
            )
        );
    }
}